package org.diysearch.dao.impls;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.diysearch.dao.interfaces.PageDao;
import org.diysearch.models.Page;
import org.diysearch.models.PageElement;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

public class PageDaoImpl extends SqlMapClientDaoSupport implements PageDao {
	private static final Log LOG = LogFactory.getLog(PageDaoImpl.class);
	
	@Override
	public List<Page> findByPublished() throws SQLException {
		return getSqlMapClientTemplate().queryForList("findAllPublishedPages",null);
	}

	@Override
	public List<Page> findByUnpublished() throws SQLException {
		return getSqlMapClientTemplate().queryForList("findAllUnpublishedPages",null);
	}

	@Override
	public Page findByUri(Page page) throws SQLException {
		return (Page) getSqlMapClientTemplate().queryForObject("findPageByUri",page);
	}

	@Override
	public int save(Page page) throws SQLException {
		int code = 0;
		if (page.getId() == 0) {
			Page _p = (Page) getSqlMapClientTemplate().insert("insert-page",page);
			code = _p.getId();
			for (PageElement pe : page.getElements()) {
				pe.setPid(_p.getId());
				PageElement _pe = (PageElement) getSqlMapClientTemplate().insert("insert-page-element",pe);
			}
		} else {
			code += getSqlMapClientTemplate().update("update-page",page);
			for (PageElement pe : page.getElements()) {
				// start here!
				code += getSqlMapClientTemplate().update("update-pageelement",pe);
			}
		}
		return code;
	}

	@Override
	public int saveElement(PageElement pe) throws SQLException {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int setPublish(Page page) throws SQLException {
		return getSqlMapClientTemplate().update("update-publish",page);
	}

	@Override
	public int setPublishable(Page page) throws SQLException {
		return getSqlMapClientTemplate().update("update-publishable",page);
	}

}
